/*
 * 判断obj是否为一个整数
 */
function isInteger(obj) {
  return Math.floor(obj) === obj;
}

/*
 * 将一个浮点数转成整数，返回整数和倍数。如 3.14 >> 314，倍数是 100
 * @param floatNum {number} 小数
 * @return {object}
 *   {times:100, num: 314}
 */
function toInteger(floatNum) {
  let ret = { times: 1, num: 0 };
  floatNum = Number(floatNum);
  let isNegative = floatNum < 0;
  if (isInteger(floatNum)) {
    ret.num = floatNum;
    return ret;
  }
  let strfi = floatNum + '';
  let dotPos = strfi.indexOf('.');
  let len = strfi.substr(dotPos + 1).length;
  console.log("JJLog:现在是=====：" + len);
  let times = Math.pow(10, len);
  let intNum = parseInt(Math.abs(floatNum) * times + 0.5, 10);
  ret.times = times;
  if (isNegative) {
    intNum = -intNum;
  }
  ret.num = intNum;
  console.log("JJLog:哈哈哈哈：" + JSON.stringify(ret));
  return ret;
}

/*
 * 核心方法，实现加减乘除运算，确保不丢失精度
 * 思路：把小数放大为整数（乘），进行算术运算，再缩小为小数（除）
 *
 * @param a {number} 运算数1
 * @param b {number} 运算数2
 * @param op {string} 运算类型，有加减乘除（add/subtract/multiply/divide）
 *
 */
function operation(a, b, op) {
  let o1 = toInteger(a);
  let o2 = toInteger(b);
  let n1 = o1.num;
  let n2 = o2.num;
  let t1 = o1.times;
  let t2 = o2.times;
  let max = t1 > t2 ? t1 : t2;
  let result = null;
  switch (op) {
    case 'add':
      if (t1 === t2) { // 两个小数位数相同
        result = n1 + n2;
      } else if (t1 > t2) { // o1 小数位 大于 o2
        result = n1 + n2 * (t1 / t2);
      } else { // o1 小数位 小于 o2
        result = n1 * (t2 / t1) + n2;
      }
      return result / max;
    case 'subtract':
      if (t1 === t2) {
        result = n1 - n2;
      } else if (t1 > t2) {
        result = n1 - n2 * (t1 / t2);
      } else {
        result = n1 * (t2 / t1) - n2;
      }
      return result / max;
    case 'multiply':
      result = (n1 * n2) / (t1 * t2);
      return result;
    case 'divide':
      result = (n1 / n2) * (t2 / t1);
      return result;
    default:
      return NaN;
  }
}
/**
 * 四舍五入
 * @param {*} num 数字
 * @param {*} point 小数点后几位
 */
function round(num, point) {
  if (isNaN(num)) {
    return null;
  }
  point = Math.pow(10, point + 1);
  num = num * point;
  if (num === +num) {
    return parseInt((num + 5) / 10, 10) / point * 10;
  } else {
    return +num;
  }
}

// 加减乘除的四个接口
function add(a, b) {
  return operation(a, b, 'add');
}
function sub(a, b) {
  return operation(a, b, 'subtract');
}
function mul(a, b) {
  return operation(a, b, 'multiply');
}
function div(a, b) {
  return operation(a, b, 'divide');
}

const MathUtils = {
  add,
  sub,
  mul,
  div,
  round
}

export default MathUtils;
